import pandas as pd

from src.Frame import Frame
from src.Object import Object


class FrameParser(Object):
    def __init__(self):
        self.current_frame: Frame = None
        self.df_tail = pd.DataFrame()
        self.df_result = pd.DataFrame()

    def parse_line(self, line):
        if self.current_frame is None:
            if FrameParser.is_time(line):
                self.current_frame = Frame()
                self.current_frame.add_time(line.split())
        else:
            if FrameParser.is_header(line):
                self.current_frame.add_head(line.split())
            elif FrameParser.is_content(line):
                if not self.current_frame.is_content_full():
                    self.current_frame.add_content(line.split())
            elif FrameParser.is_tail(line):
                self.current_frame.add_tail(line.split())
                self.update_frames(self.current_frame)
                # self.current_frame.add_tail(line.split())

    @staticmethod
    def is_header(line):
        elements = line.split()
        if (len(elements) == 10 or len(elements) == 6) and elements[0] == 'PID':
            return True
        else:
            return False

    @staticmethod
    def is_content(line):
        elements = line.split()
        if (len(elements) == 10 or len(elements) == 6) and elements[0].isdigit():
            return True
        else:
            return False

    @staticmethod
    def is_tail(line):
        elements = line.split()
        if len(elements) == 13 and elements[0] == 'RAM:':
            return True
        else:
            return False

    @staticmethod
    def is_time(line):
        elements = line.split()
        if len(elements) == 2 and elements[0] == 'TIME:':
            return True
        else:
            return False

    def update_frames(self, frame):
        # self.current_frame.to_string()
        self.current_frame.data_frame.drop_duplicates(subset='cmdline', inplace=True)

        ser_data = self.current_frame.data_frame['Uss'].astype(int).tolist()
        ser_index = self.current_frame.data_frame['cmdline'].tolist()
        ser = pd.Series(ser_data, index=ser_index, name=self.current_frame.current_time)

        self.df_result = self.df_result.append(ser)
        self.df_tail = self.df_tail.append(self.current_frame.tail_series.astype(int))

        self.current_frame = None

    def get_mem_rank(self):
        return self.df_result

    def get_mem_status(self):
        return self.df_tail
